<template>
  <div>
    <div class="mx-2.5 mb-5 text-left">
      <el-button type="primary" size="mini" class="!ml-2.5" @click="refresh"
        >刷新</el-button
      >
      <el-dropdown
        class="ml-2.5"
        size="mini"
        split-button
        type="success"
        @command="(cmd) => handleSelect(cmd)"
        @click="handleSelect('currentPage')"
      >
        选择(本页)
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item command="all">全部</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <el-button type="primary" size="mini" class="!ml-2.5" @click="add"
        >添加</el-button
      >
      <el-dropdown
        class="ml-2.5"
        size="mini"
        split-button
        type="danger"
        @command="(cmd) => handleSelectedRemove(cmd)"
        @click="handleSelectedRemove('selection')"
      >
        删除(选中)
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item command="all">全部</el-dropdown-item>
          <el-dropdown-item command="currentPage">本页</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>
    <div class="my-2.5 mx-5 py-2.5 px-2.5 border border-solid border-[#e6ebf5]">
      <el-table
        ref="table"
        :loading="$apollo.queries.emailTemplates.loading"
        :data="emailTemplates.items"
        fit
        highlight-current-row
        class="w-full"
        height="calc(100vh - 315px)"
        row-key="id"
        @selection-change="handleSelection"
      >
        <el-table-column
          align="center"
          type="selection"
          reserve-selection
        ></el-table-column>
        <el-table-column
          align="center"
          :label="$t('common.id')"
          width="50"
          type="index"
        />
        <el-table-column
          align="center"
          min-width="300px"
          label="标题"
          prop="title"
        >
        </el-table-column>
        <el-table-column
          width="150px"
          align="center"
          :label="$t('common.createTime')"
        >
          <template slot-scope="{ row }">
            <span v-time="row.createdAt"></span>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('table.actions')"
          align="center"
          min-width="150"
        >
          <template slot-scope="{ row }">
            <el-button size="mini" @click="edit(row)" type="primary" plain>
              {{ $t('table.edit') }}
            </el-button>
            <el-button
              slot="reference"
              size="mini"
              type="danger"
              plain
              @click="handleDelete(row)"
              >{{ $t('common.delete') }}</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <pagination
        class="text-left"
        v-show="emailTemplates.totalCount > 0"
        :total="emailTemplates.totalCount"
        :page.sync="pageInfo.page"
        :limit.sync="pageInfo.limit"
        :page-sizes="[10, 20, 30, 50, 100, 200]"
      />
    </div>
    <AddTemplate
      :show.sync="addTemplateVisible"
      :id.sync="templateId"
      @closeAction="handleTemplateDialogClosed"
    />
  </div>
</template>

<script>
import { getAction } from '@/api/common'
import Pagination from '@/components/Pagination/index.vue'
import { EmailModule } from '@/store/modules/email'
import gql from 'graphql-tag'
import AddTemplate from './addTemplate.vue'
export default {
  name: 'templateList',
  components: { Pagination, AddTemplate },
  props: {
    templates: {
      type: [Array],
      default: () => [],
    },
  },
  apollo: {
    emailTemplates: {
      query: gql`
        query GetEmailTemplates(
          $skip: Int!
          $take: Int!
          $where: EmailTemplateFilterInput
        ) {
          emailTemplates(skip: $skip, take: $take, where: $where) {
            items {
              id
              title
              type
              attribute
              createdAt
              updatedAt
            }
            totalCount
          }
        }
      `,
      variables() {
        let take = this.pageInfo.limit
        let skip = (this.pageInfo.page - 1) * take
        let where = {}
        return {
          where,
          take,
          skip,
        }
      },
      result({ data }) {
        console.log(data)
        const checkedTemplates = EmailModule.context.state.checkedTemplates
        if (this.selection.length === 0 && checkedTemplates.length > 0) {
          for (let item of data.emailTemplates.items) {
            if (checkedTemplates.includes(item.id)) {
              this.$refs.table.toggleRowSelection(item, true)
            }
          }
        }
      },
    },
  },
  inject: ['showProgressDialog'],
  data() {
    return {
      emailTemplates: {},
      pageInfo: {
        page: 1,
        limit: 100,
      },
      addReceiverVisible: false,
      addReceiverForm: {
        email: '',
        name: '',
        phone: '',
      },
      selection: [],
      templateId: '',
      addTemplateVisible: false,
    }
  },
  created() {},
  computed: {},
  methods: {
    refresh() {
      const waitRefreshDone = (query) => {
        if (query.loading) {
          return new Promise((resolve) => {
            setTimeout(() => {
              resolve(waitRefreshDone(query))
            }, 100)
          })
        } else {
          return Promise.resolve()
        }
      }
      this.$apollo.queries.emailTemplates.refresh()
      return waitRefreshDone(this.$apollo.queries.emailTemplates)
    },
    async handleDelete(row) {
      this.$confirm(this.$t('customer.confirmDelete'), this.$t('common.tips'), {
        confirmButtonText: this.$t('common.confirm'),
        cancelButtonText: this.$t('common.cancel'),
        type: 'warning',
      })
        .then(() => {
          getAction({ id: row.id }, 'EmailTemplate/Delete').then((res) => {
            if (res.code === 20000) {
              this.$message({
                message: this.$t('common.deleteSuccessfully'),
                type: 'success',
              })
              this.refresh()
            } else {
              this.$message({
                message: this.$t('email.deleteFailed'),
                type: 'warning',
              })
            }
          })
        })
        .catch(async () => {
          console.log('catch')
        })
    },
    getFilterRows(command) {
      let result
      if (command === 'currentPage') {
        result = this.emailTemplates.items
      } else if (command === 'all') {
        result = this.emailTemplates.items
      } else if (command === 'selection') {
        result = this.selection
      }
      return result
    },
    handleSelect(command) {
      if (command === 'currentPage') {
        this.$refs.table.toggleAllSelection()
      } else {
        let rows = this.getFilterRows(command)
        for (let item of rows) {
          this.$refs.table.toggleRowSelection(item, true)
        }
      }
    },
    handleSelection(val) {
      this.selection = val
      EmailModule.SET_EMAIL_CHECKED_TEMPLATES(this.selection.map((s) => s.id))
      this.$emit('update:templates', val)
    },
    handleSelectedRemove(command) {
      let rows = this.getFilterRows(command)
      if (rows.length <= 0) {
        this.$message(this.$t('customer.checkDataNeedToBatchDelete'))
        return false
      }
      const uploadItems = [
        {
          name: '模板',
          num: rows.length,
          action: this.batchDeleteFunc,
          data: rows,
        },
      ]
      const uploadColumns = []
      this.showProgressDialog(uploadItems, uploadColumns, this.refresh, {
        title: this.$t('common.batchDeleteCantReverse'),
      })
    },
    batchDeleteFunc({ item, message }) {
      this.getAction({ id: item.id }, 'EmailTemplate/Delete')
        .then((res) => {
          let it = this.selection.find((m) => m.id === item.id)
          if (it) {
            this.$refs.table.toggleRowSelection(it, false)
          }
          message.success('[' + item.name + '] 删除成功')
        })
        .catch((res) => {
          message.failed('[' + item.name + '] ' + res.message)
        })
    },
    add() {
      this.templateId = ''
      this.addTemplateVisible = true
    },
    edit(row) {
      this.addTemplateVisible = true
      this.templateId = row.id
    },
    randomSelect() {
      this.$refs.table.clearSelection()
      for (let row of this.emailTemplates.items) {
        let checked = Math.random() > 0.5
        if (checked) this.$refs.table.toggleRowSelection(row, true)
      }
    },
    async handleTemplateDialogClosed(id) {
      await this.refresh()
      const row = this.emailTemplates.items.find((t) => t.id === id)
      if (row) this.$refs.table.toggleRowSelection(row, true)
    },
  },
}
</script>

<style scoped></style>
